package chinasoft.learn;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by zhour on 2017/8/3.
 */
public class SocketInfo {

    @SocketValue(start = 0,end = 2)
    private String aaa;
    @SocketValue(start = 3,end = 5)
    private String bbb;

    public String getAaa() {
        return aaa;
    }

    public void setAaa(String aaa) {
        this.aaa = aaa;
    }

    public String getBbb() {
        return bbb;
    }

    public void setBbb(String bbb) {
        this.bbb = bbb;
    }

    public void init(String sockeBytes) {
        Field[] fields = this.getClass().getDeclaredFields();
        // 遍历所有属性
        String name;
        Field field;
        SocketValue socketValue;
        String value;
        Method m;
        try {
            for (int j = 0; j < fields.length; j++) {
                field = fields[j];
                // 获取属性的名字
                // 将属性的首字符大写，方便构造get，set方法
                name = field.getName();
                name = name.substring(0, 1).toUpperCase() + name.substring(1);
                if (field.isAnnotationPresent(SocketValue.class)) {
                    socketValue = field.getAnnotation(SocketValue.class);
                    int start = socketValue.start();
                    int end = socketValue.end();

                    value = sockeBytes.substring(start,end);
                    m = this.getClass().getMethod("set" + name,field.getType());
                    if (field.getType() == Integer.class){
                        m.invoke(this,Integer.parseInt(value));
                    } else if(field.getType() == String.class){
                        m.invoke(this,value);
                    } else if(field.getType() == Long.class){
                        m.invoke(this,Long.parseLong(value));
                    } else if(field.getType() == Short.class){
                        m.invoke(this,Short.parseShort(value));
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
